/*
 * Copyright (C) 2012 Stephane Ribas
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ribas.stephane;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.ribas.stephane.db.DatabaseHelper;

/**
 * This is the activity for feature 4 in the dashboard application.
 * It displays some text and provides a way to get back to the home activity.
 *
 */

public class AffectionsActivity extends ListActivity 
{

// variable pour le debug ;-)
private static final String TAG = "StatusActivity";

//MENU OPTIONS
// Button QUIT + SETTINGS
final private static int optionGroupId = 1;
final private static int optionRemedesItemId = 1;
final private static int optionRemedesOrder = 1;
final private static int optionQuitItemId = 2;
final private static int optionQuitOrder = 2;

// BDD declaration
protected EditText searchText;
protected SQLiteDatabase db;
protected Cursor cursor;
protected ListAdapter adapter;
protected ListView affectionsList;

// START
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    
    super.onCreate(savedInstanceState);
    setTitleFromActivityLabel (R.id.titleAffections);  
    setContentView(R.layout.activity_affectionslist);
   
    // Search field
    searchText = (EditText) findViewById (R.id.searchText);
    
    // db
    db = (new DatabaseHelper(this)).getWritableDatabase();
    fillListView();   
}

@Override
public void onListItemClick(ListView parent, View view, int position, long id) {
 	Log.d(TAG, "LIST CLICK");
 	Intent intent = new Intent(this, AffectionsDetailsActivity.class);
 	Cursor cursor = (Cursor) adapter.getItem(position);
 	intent.putExtra("NOM_ID", cursor.getInt(cursor.getColumnIndex("_id")));
 	startActivity(intent);
 }

public void onClickSearch(View view) {
	Log.d(TAG, "OnClick Search");
	 // || is the concatenation operation in SQLite
	//cursor = db.rawQuery("SELECT _id, Nom, Description, Traitement FROM listeaffections WHERE Nom || ' ' || Description || ' ' || Traitement  LIKE ?", 
	//				new String[]{"%" + searchText.getText().toString() + "%"});
	cursor = db.rawQuery("SELECT affec._id, affec.Nom, affec.Description, affec.Traitement FROM listeaffections affec WHERE affec.Nom || ' ' || affec.Description || ' ' || affec.Traitement  LIKE ?", 
			new String[]{"%" + searchText.getText().toString() + "%"});

	adapter = new SimpleCursorAdapter(
			this, 
			R.layout.activity_affectionslist_item, 
			cursor, 
			new String[] {"Nom", "Description"}, 
			new int[] {R.id.Nom, R.id.Description});
	setListAdapter(adapter);
	
}

// fillView with list of affection by alphabetic order
public void fillListView() {
	cursor = db.rawQuery("SELECT _id, Nom, Description FROM listeaffections WHERE Nom = Nom ORDER By Nom", null);
	adapter = new SimpleCursorAdapter(
			this, 
			R.layout.activity_affectionslist_item, 
			cursor, 
			new String[] {"Nom", "Description"}, 
			new int[] {R.id.Nom, R.id.Description});
	setListAdapter(adapter);
}

//
// CLOSE la BDD en quittant l'application
//
public void onStop(Bundle savedInstanceState) {
	Log.d(TAG, "QUIT via onStop");
	db.close();
}

/**
 */
// Click Methods

/**
 * Handle the click on the home button.
 * 
 * @param v View
 * @return void
 */

public void onClickHome (View v)
{
    goHome (this);
}


/**
 * Handle the click on the HELP button.
 * 
 * @param v View
 * @return void
 */

public void onClickHelp (View v)
{
    startActivity (new Intent(getApplicationContext(), HelpActivity.class));
}
/**
 * Handle the click on the About button.
 * 
 * @param v View
 * @return void
 */

public void onClickAbout (View v)
{
    startActivity (new Intent(getApplicationContext(), AboutActivity.class));
}

/**
 * Handle the click on the Quit button.
 * 
 * @param v View
 * @return void
 */

public void onClickQuit (View v)
{
	finish();
}

/**
 * onDestroy
 * The final call you receive before your activity is destroyed. 
 * This can happen either because the activity is finishing (someone called finish() on it, 
 * or because the system is temporarily destroying this instance of the activity to save space. 
 * You can distinguish between these two scenarios with the isFinishing() method.
 *
 */


protected void onDestroy ()
{
    Log.d(TAG, "Destroy");
    if (db != null) db.close();
	super.onDestroy ();
}

/**
 * Go back to the home activity.
 * 
 * @param context Context
 * @return void
 */

public void goHome(Context context) 
{
    final Intent intent = new Intent(context, HomeoGratuitHomeActivity.class);
    intent.setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP);
    context.startActivity (intent);
}

/**
 * Use the activity label to set the text in the activity's title text view.
 * The argument gives the name of the view.
 *
 * <p> This method is needed because we have a custom title bar rather than the default Android title bar.
 * See the theme definitons in styles.xml.
 * 
 * @param textViewId int
 * @return void
 */

public void setTitleFromActivityLabel (int textViewId)
{
    TextView tv = (TextView) findViewById (textViewId);
    if (tv != null) tv.setText (getTitle ());
} // end setTitleText

/**
 * Show a string on the screen via Toast.
 * 
 * @param msg String
 * @return void
 */

public void toast (String msg)
{
    Toast.makeText (getApplicationContext(), msg, Toast.LENGTH_SHORT).show ();
} // end toast

/**
 * Send a message to the debug log and display it using Toast.
 */
public void trace (String msg) 
{
    Log.d("HOMEOGRATUIT", msg);
    toast (msg);
}

/* (non-Javadoc)
 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
 * declaration des menus qui apparait lorsque l'on fait OPTION sur le tel.
 * implementer : Button QUITTER, SETTINGS
 * reste a faire: faire apparaitre SETTINGS...
 */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
	menu.add(optionGroupId,optionRemedesItemId, optionRemedesOrder, getString(R.string.optionRemedes));
	return super.onCreateOptionsMenu(menu);
}

/* (non-Javadoc)
 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
 *
 * declaration des actions du menu OPTION
 * implementer : Button QUITTER
 * reste a faire: SETTINGS... etc
 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
	switch (item.getItemId()) {
		case optionRemedesItemId:
		startActivity (new Intent(getApplicationContext(), RemedesActivity.class));
        break;
	}
	return super.onOptionsItemSelected(item);
}


    
} // end class
